/* eslint-disable @typescript-eslint/no-explicit-any */
import { createRouter } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { routerConfig } from '@/router/config'
import { registerNavigationGuard } from './guard'

const Layouts = () => import('@/layouts/index.vue')

/**
 * @name 常驻路由
 * @description 除了 redirect/403/404/login 等隐藏页面，其他页面建议设置唯一的 Name 属性
 */

export const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      hidden: true,
    },
  },
  {
    path: '/404',
    component: () => import('@/views/error/404.vue'),
    meta: {
      hidden: true,
    },
    // 定义路由的别名
    // /:pathMatch(.*)* 是一个动态路径参数，可以匹配 任何未定义的路由路径（类似通配符）
    alias: '/:pathMatch(.*)*',
  },
  {
    path: '/403',
    component: () => import('@/views/error/403.vue'),
    meta: {
      hidden: true,
    },
  },
  {
    path: '/',
    redirect: '/dashboard',
    // 所有子路由共享 Layouts 组件（通常包含导航栏、侧边菜单等）
    component: Layouts,
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        name: 'Dashboard',
        meta: {
          title: '首页', // 可用于面包屑或浏览器
          affix: true, // 标记该路由对应的标签页是否固定
          svgIcon: 'dashboard',
        },
      },
    ],
  },
  {
    path: '/demo',
    component: Layouts,
    redirect: '/demo/unocss',
    name: 'Demo',
    meta: {
      title: '示例集合',
      elIcon: 'DataBoard',
    },
    children: [
      {
        path: 'unocss',
        component: () => import('@/views/demo/unocss/index.vue'),
        name: 'UnoCSS',
        meta: {
          title: 'UnoCSS',
        },
      },
      {
        path: 'element-plus',
        component: () => import('@/views/demo/element-plus/index.vue'),
        name: 'ElementPlus',
        meta: {
          title: 'Element Plus',
          keepAlive: true,
        },
      },
      {
        path: 'vxe-table',
        component: () => import('@/views/demo/vxe-table/index.vue'),
        name: 'VxeTable',
        meta: {
          title: 'Vxe Table',
          keepAlive: true,
        },
      },
      {
        path: 'level2',
        component: () => import('@/views/demo/level2/index.vue'),
        redirect: '/demo/level2/level3',
        name: 'Level2',
        meta: {
          title: '二级路由',
          alwaysShow: true,
        },
        children: [
          {
            path: 'level3',
            component: () => import('@/views/demo/level2/level3/index.vue'),
            name: 'Level3',
            meta: {
              title: '三级路由',
              keepAlive: true,
            },
          },
        ],
      },
      {
        path: 'composable-demo',
        redirect: '/demo/composable-demo/use-fetch-select',
        name: 'ComposableDemo',
        meta: {
          title: '组合式函数',
        },
        children: [
          {
            path: 'use-fetch-select',
            component: () =>
              import('@/views/demo/composable-demo/use-fetch-select.vue'),
            name: 'UseFetchSelect',
            meta: {
              title: 'useFetchSelect',
            },
          },
          {
            path: 'use-fullscreen-loading',
            component: () =>
              import('@/views/demo/composable-demo/use-fullscreen-loading.vue'),
            name: 'UseFullscreenLoading',
            meta: {
              title: 'useFullscreenLoading',
            },
          },
          {
            path: 'use-watermark',
            component: () =>
              import('@/views/demo/composable-demo/use-watermark.vue'),
            name: 'UseWatermark',
            meta: {
              title: 'useWatermark',
            },
          },
        ],
      },
    ],
  },
  {
    path: '/link',
    meta: {
      title: '文档链接',
      elIcon: 'Link',
    },
    children: [
      {
        path: 'https://juejin.cn/post/7445151895121543209',
        component: () => {},
        name: 'Link1',
        meta: {
          title: '中文文档',
        },
      },
      {
        path: 'https://juejin.cn/column/7207659644487139387',
        component: () => {},
        name: 'Link2',
        meta: {
          title: '新手教程',
        },
      },
    ],
  },
  {
    path: '/dataShow',
    component: Layouts,
    meta: {
      title: '数据展示',
      elIcon: 'PieChart',
    },
    children: [
      {
        path: '', // 空路径表示这是父路由的直接内容
        component: () => import('@/views/dataShow/index.vue'),
        name: 'DataShow',
        meta: {
          title: '数据展示',
          elIcon: 'PieChart',
        },
      },
    ],
  },
]

export const dynamicRoutes: RouteRecordRaw[] = [
  {
    path: '/permission',
    component: Layouts,
    redirect: '/permission/page-level',
    name: 'Permission',
    meta: {
      title: '权限演示',
      elIcon: 'Lock',
      // 可以在根路由中设置角色
      roles: ['admin', 'editor'],
      alwaysShow: true,
    },
    children: [
      {
        path: 'page-level',
        component: () => import('@/views/demo/permission/page-level.vue'),
        name: 'PermissionPageLevel',
        meta: {
          title: '页面级',
          // 或者在子路由中设置角色
          roles: ['admin'],
        },
      },
      {
        path: 'button-level',
        component: () => import('@/views/demo/permission/button-level.vue'),
        name: 'PermissionButtonLevel',
        meta: {
          title: '按钮级',
          // 如果未设置角色，则表示：该页面不需要权限，但会继承根路由的角色
          roles: undefined,
        },
      },
    ],
  },
]

// 导出路由实例
export const router = createRouter({
  history: routerConfig.history,
  // 路由降级选项
  routes: routerConfig.thirdLevelRouteCache ? constantRoutes : constantRoutes,
})

// 重置路由
export function resetRouter() {
  try {
    // 注意：所有动态路由路由必须带有name属性，否则可能会不能完全重置干净
    router.getRoutes().forEach((route: any) => {
      // 解构name、meta
      const { name, meta } = route
      // 移除动态添加的路由保留基础路由
      // 通过meta.roles判断是否为权限路由
      if (name && meta.roles?.length && router.hasRoute(name)) {
        router.removeRoute(name)
      }
    })
  } catch {
    // 强制刷新浏览器，只是交互体验不是很好
    location.reload()
  }
}

// 注册路由导航守卫
registerNavigationGuard(router)
